import os  # 新增导入
from datetime import datetime

import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("weather-forecast-server", host="0.0.0.0", port=8080)

# 从环境变量获取 OpenWeatherMap API Key
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")  # 从环境变量读取
if not OPENWEATHER_API_KEY:
    raise ValueError("请设置环境变量 OPENWEATHER_API_KEY")

OPENWEATHER_API_URL = "https://api.openweathermap.org/data/2.5/weather"
OPENWEATHER_FORECAST_API_URL = "https://api.openweathermap.org/data/2.5/forecast"


@mcp.tool()
def get_current_weather(city: str) -> dict:
    """获取指定城市的当前天气情况

    Args:
        city: 城市名称 (例如: "Beijing", "Shanghai")

    Returns:
        dict: 包含当前天气数据的字典（字段已转换为中文）
    """
    try:
        params = {
            "q": city,
            "appid": OPENWEATHER_API_KEY,
            "units": "metric",  # 使用摄氏度
            "lang": "zh_cn"  # 返回中文描述
        }

        response = httpx.get(OPENWEATHER_API_URL, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()

        # 解析 OpenWeatherMap 返回的数据
        weather_info = {
            "code": "20000",
            "message": "success",
            "data": {
                "city": data.get("name", city),
                "current_conditions": {
                    "temperature": data["main"]["temp"],  # 温度(℃)
                    "feels_like": data["main"]["feels_like"],  # 体感温度(℃)
                    "weather": data["weather"][0]["description"],  # 天气状况
                    "humidity": data["main"]["humidity"],  # 湿度(%)
                    "wind_speed": data["wind"]["speed"],  # 风速(m/s)
                    "wind_direction": data["wind"].get("deg", "未知"),  # 风向(度)
                    "pressure": data["main"]["pressure"],  # 气压(hPa)
                    "visibility": data.get("visibility", "未知"),  # 能见度(米)
                    "update_time": datetime.fromtimestamp(data["dt"]).strftime("%Y-%m-%d %H:%M:%S")
                }
            }
        }

        # 字段映射为中文
        field_mapping = {
            "temperature": "温度(℃)",
            "feels_like": "体感温度(℃)",
            "weather": "天气状况",
            "humidity": "湿度(%)",
            "wind_speed": "风速(m/s)",
            "wind_direction": "风向(度)",
            "pressure": "气压(hPa)",
            "visibility": "能见度(米)",
            "update_time": "更新时间"
        }

        # 转换字段名
        translated_conditions = {}
        for key, value in weather_info["data"]["current_conditions"].items():
            if key in field_mapping:
                translated_conditions[field_mapping[key]] = value
            else:
                translated_conditions[key] = value

        weather_info["data"]["current_conditions"] = translated_conditions
        return weather_info

    except Exception as e:
        return {"code": "50000", "message": f"获取天气数据失败: {str(e)}", "data": None}


@mcp.tool()
def get_weather_forecast(city: str, days: int = 3) -> dict:
    """获取指定城市的天气预报

    Args:
        city: 城市名称
        days: 预报天数 (1-5)

    Returns:
        dict: 包含天气预报数据的字典（字段已转换为中文）
    """
    try:
        params = {
            "q": city,
            "appid": OPENWEATHER_API_KEY,
            "units": "metric",
            "lang": "zh_cn",
            "cnt": days * 8  # 每天8个数据点（3小时间隔）
        }

        response = httpx.get(OPENWEATHER_FORECAST_API_URL, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()

        # 解析预报数据
        forecast_data = {
            "code": "20000",
            "message": "success",
            "data": {
                "city": data["city"]["name"],
                "forecast_days": days,
                "forecasts": []
            }
        }

        # 按天聚合数据（OpenWeatherMap 返回的是 3 小时间隔的数据）
        daily_data = {}
        for item in data["list"]:
            date = datetime.fromtimestamp(item["dt"]).strftime("%Y-%m-%d")
            if date not in daily_data:
                daily_data[date] = {
                    "date": date,
                    "day_weather": item["weather"][0]["description"],
                    "high_temp": item["main"]["temp_max"],
                    "low_temp": item["main"]["temp_min"],
                    "humidity": item["main"]["humidity"],
                    "wind_speed": item["wind"]["speed"],
                    "wind_direction": item["wind"].get("deg", "未知")
                }
            else:
                # 更新最高/最低温度
                if item["main"]["temp_max"] > daily_data[date]["high_temp"]:
                    daily_data[date]["high_temp"] = item["main"]["temp_max"]
                if item["main"]["temp_min"] < daily_data[date]["low_temp"]:
                    daily_data[date]["low_temp"] = item["main"]["temp_min"]

        forecast_data["data"]["forecasts"] = list(daily_data.values())

        # 字段映射为中文
        field_mapping = {
            "date": "日期",
            "day_weather": "天气状况",
            "high_temp": "最高温度(℃)",
            "low_temp": "最低温度(℃)",
            "humidity": "湿度(%)",
            "wind_speed": "风速(m/s)",
            "wind_direction": "风向(度)"
        }

        # 转换字段名
        translated_forecasts = []
        for forecast in forecast_data["data"]["forecasts"]:
            translated_forecast = {}
            for key, value in forecast.items():
                if key in field_mapping:
                    translated_forecast[field_mapping[key]] = value
                else:
                    translated_forecast[key] = value
            translated_forecasts.append(translated_forecast)

        forecast_data["data"]["forecasts"] = translated_forecasts
        return forecast_data

    except Exception as e:
        return {"code": "50000", "message": f"获取天气预报失败: {str(e)}", "data": None}


if __name__ == "__main__":
    mcp.run(transport='sse')